<?php
namespace App\Service\Admin;

class AddressService extends BaseService
{
    //收货地址

    public static function index()
    {
        $db = self::dbConn(self::$dbAddress)->where('del', 0);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $wxOne = self::dbConn(self::$dbWx)->where('id', $v->uid)->first();
            $v->uname = $wxOne ? $wxOne->nickName : '-';
        }
        return self::toback(0, '', $res, $total);
    }

    /**
     * 新增
     * @param array $pas
     */
    public static function add($uname, $pas)
    {
        $uOne = self::dbConn(self::$dbWx)->where('nickName', $uname)->first();
        if (!$uOne) {
            return self::toback(-2, '没有用户');
        }
        $pas['uid'] = $uOne->id;
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = self::dbConn(self::$dbAddress)->insertGetId($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas
     */
    public static function modify($id, $uname, $pas)
    {
        $uOne = self::dbConn(self::$dbWx)->where('nickName', $uname)->first();
        if (!$uOne) {
            return self::toback(-2, '没有用户');
        }
        $pas['uid'] = $uOne->id;
        $pas['uptime'] = toDate();
        $up = self::dbConn(self::$dbAddress)
            ->where('id', $id)
            ->update($pas);
        if (!$up) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    /**
     * 删除
     * @param int $id 场景ID
     * return array
     */
    public static function del($id)
    {
        $pas = [
            'del' => 1,
        ];
        $res = self::dbConn(self::$dbAddress)
            ->where('id', $id)
            ->update($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }
}